package com.by.controller;


import com.by.common.bean.ResultBean;
import com.by.common.controller.BaseController;
import com.by.common.utils.DateUtils;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Api(tags = "文件上传")
@RequestMapping("/v1")
@RestController
public class UploadController extends BaseController {

    final String DIR = "/attachment";
    final Set<String> imgSet = new HashSet<>();

    /**
     * 初始化图片类型
     */
    {
        imgSet.add("image/jpeg");
        imgSet.add("image/png");
    }

    /**
     * 上传图片类型的文件
     * @param file 要上传的文件
     * @param request  请求域对象 可以获取服务器的存储目录
     * @return
     */
    @ApiOperation("上传图片类型的文件")
    @PostMapping("/upload/img")
    public ResultBean uploadImg(MultipartFile file, HttpServletRequest request) {
        String type = file.getContentType();//获取文件类型
        if (!imgSet.contains(type)){
            return fail("请上传：jpg，png格式的文件！");
        }
        String path=upload(file,request,type);
        return success("上传成功",path);
    }

    @ApiOperation("上传音频类型的文件")
    @PostMapping("/upload/video")
    public ResultBean uploadVideo(MultipartFile file, HttpServletRequest request) {
        String type = file.getContentType();//获取文件类型
        if (!type.equals("video")){
            return fail("请上传：video格式的文件！");
        }
        String path=upload(file,request,type);
        return success("上传成功",path);
    }

    /**
     * 上传功能
     *
     * @param file
     * @param request
     * @param type
     * @return
     */
    public String upload(MultipartFile file, HttpServletRequest request, String type) {
        String fileName = file.getOriginalFilename();//获取原始文件名
        String ext = getExt(fileName);//获取文件后缀
        String newFileName = System.currentTimeMillis() + ext;//生成新的文件名

        String root = request.getServletContext().getRealPath("/");//获取服务器根目录
        String tmpDir = DIR + "/" + type + "/" + DateUtils.getYmd();//和当前系统时间拼接多层文件夹
        File dirFile = new File(root + tmpDir);//文件的存放路径
        if (!dirFile.exists()) {
            dirFile.mkdirs();//创建目录
            //将上传的文件拷贝到指定目录
            try {
                file.transferTo(new File(dirFile, newFileName));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        String path = tmpDir + "/" + newFileName;
        System.out.println(path);
        return path;
    }

    public String getExt(String fileName) {
        int pos = fileName.lastIndexOf(".");
        return fileName.substring(pos);
    }
}
